package cn.jussi.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.swing.Timer;

import cn.jussi.mvcproject.model.Online;
import cn.jussi.mvcproject.service.FactoryService;
import cn.jussi.mvcproject.service.OnlineService;

@WebListener
public class OnlineServletContextListener implements ServletContextListener {
	
	/**
	 * 10分钟，访问者超过设置的时间没有操作,离线
	 */
	public final int Max_MILLIS = 10*60*1000;
	
	OnlineService onlineService = FactoryService.getOnlineService();
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		//存放过时的访问者的信息
		List<Online> expiresUserList = new ArrayList<>();
		
		//定时器
		new Timer(5*1000, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent event) {
				List<Online> list = onlineService.getAllOnline();
				if(list != null && list.size()>0) {
					for(Online ol: list) {
						if((System.currentTimeMillis()-ol.getTime().getTime())>Max_MILLIS) {
							expiresUserList.add(ol);
						}
					}	
				}
				onlineService.deleteExpiresOnline(expiresUserList);
				expiresUserList.clear();
			}
		}).start();
	}

}
